<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="年月" prop="planMonth">
        <el-date-picker clearable
                        v-model="queryParams.planMonth"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="选择排产月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="产地" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择" filterable clearable @change="factoryChange">
          <el-option v-for="team in factoryList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" filterable clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="产品编码" prop="bomCode">
        <el-input v-model="queryParams.bomCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="bomName">
        <el-input v-model="queryParams.bomName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery(false)">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
<!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery(true)">搜索(Mock数据)</el-button>-->
      </el-form-item>
    </el-form>

    <el-table v-loading="loading"
                ref="multipleTable"
                border style="width:100%;"
                :data="bigPanList"
                :span-method="planDateSpanMethod"
                @cell-click="handleCellClick">
        <el-table-column label="序号" type="index">
        </el-table-column>
        <el-table-column
          prop="planDate"
          label="日期"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="teamName"
          label="班组"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column align='center' label="排产情况计划视图">
          <el-table-column
            v-for="column in columnList" :key="column.prop"
            :label="column.label"
            v-if="column.prop !=='planDate' && column.prop !=='teamName' "
            :prop="column.prop"
            :width="column.width"
            align="center"
            v-bind="column">
            <template slot-scope="scope">
              <div :style="getCellStyles(scope.row, column.prop)" v-if="scope.row[column.prop]!=null">
                <span v-if="scope.row[column.prop] != null">
                  {{scope.row[`detail_${column.prop}`]['planCapacity']}}/{{scope.row[`detail_${column.prop}`]['finishedNum']}}
                  <el-progress :color="customColorMethod"
                               :text-inside="true"
                               :stroke-width="26"
                               :percentage="scope.row[`detail_${column.prop}`]['percentage']">
                  </el-progress>
                </span>
                <span v-html="scope.row[column.prop]"></span>
              </div>
              <div v-else>
                <span><br/><br/><br/></span>
              </div>
            </template>
            <!--<template slot-scope="scope" slot="header">
              <span>
                    {{column.label}}
                  <el-tooltip
                    :aa="scope"
                    class="item"
                    effect="dark"
                    :content="tipContent"
                    placement="top-start"
                  >
                    <i class="el-icon-warning" style="color:#66B1FF; margin-left:5px;'"> </i>
                  </el-tooltip>
                </span>
            </template>-->
          </el-table-column>
          <!-- 自定义 -->
<!--          <el-table-column-->
<!--            label="产能"-->
<!--            prop="planCapacityDesc"-->
<!--            align="center"-->
<!--            width="100">-->
<!--            <template slot-scope="scope">-->
<!--              {{scope.row.planCapacityDesc}}-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table-column>
    </el-table>

<!--    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"-->
<!--      @pagination="getList" />-->

  </div>
</template>

<script>
import {  bigPanListOfAll } from "@/api/sm/order/orderplan";
import { listTeam,listFactory } from "@/api/system/dept";
import { listChildren } from "@/api/sm/basic/bominfo";

export default {
  name: "Orderinfo",
  dicts: ['order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: false,
      calShow: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      teamSelect: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      plantotal: 0,
      //分厂待排产订单信息表格数据
      factoryWorkOrderList: [],
      //排产工单,排产计算得到的结果
      mplanProductVOList: [],
      //排产结果
      planResultList: [],
      factoryList: [],
      teamList: [],
      planStatusList: [
        {
          "label": "待排产",
          "value": 0
        }
        ,
        {
          "label": "排产完成",
          "value": 1
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamId: null,
        bomCode: null,
        bomName: null,
        mplanStatus: 0,
        workerConfirmstatus: 1,
        workerOrdertype: 1,
        excludeIds: [],
        planMonth: null,
      },
      // 表单参数
      form: {
        teamId: null,
        planMonth: null,
        chooseMonth: null,
        workOrderIds: null
      },
      // 表单参数
      form1: {
        planMonth: null,
        mplanList: null
      },
      // 表单校验
      rules: {
      },
      // 统计数据
      teamName: "导管鞘组",
      selectedCount: 18,
      standardCapacity: 20000,
      restDays: 20,
      totalStandardCapacity: 60000,
      restCapacity: 3000,
      needCapacity: 5000,
      action: null,

      tipContent: "",
      bigPanList: [],
      columnList:[],
    };
  },
  created() {
    this.tipContent = this.$createElement('div', { domProps: { innerHTML: '排产数量/已完工数量<br/>生产进度<br/>产品名称<br/>产品编码' } });

    this.init();
    this.getList();
    this.getFactoryList();
  },
  methods: {
    load(tree, treeNode, resolve) {
      console.log(tree);
      let data = {
        "parentBomCode": tree.bomCode,
        "productId": tree.productId,
        "orderCode": tree.orderCode,
        "customName": tree.customName,
        "sampleNum": tree.sampleNum ? tree.sampleNum : 0,
        "workerOrdernum": tree.workerOrdernum ? tree.workerOrdernum : 0,
        // "semiProductPlanNum": tree.semiProductPlanNum ? tree.semiProductPlanNum : tree.planNum
      };
      listChildren(data).then((res) => {   //getChildMenu是我们自己的调用后台的封装
        resolve(                            //resolve是组件的
          res.data  //根据自己的格式,将查到的子菜单数组填充
        )
      })
    },
    format(percentage) {
      return `完成度: ${percentage}%`;
    },
    customColorMethod(percentage) {
      if (percentage < 10) {
        return '#f56c6c';
      } else if (percentage < 30) {
        return '#909399';
      } else if (percentage < 70) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    },
    planDateSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) { // 指定需要合并的列索引，这里是 'planDate' 列
        let rowspan = 1;
        let colspan = 1;
        if (rowIndex > 0 && row.planDate === this.bigPanList[rowIndex - 1].planDate) {
          rowspan = 0;
        } else {
          // 计算需要合并的行数
          for (let i = rowIndex + 1; i < this.bigPanList.length; i++) {
            if (row.planDate === this.bigPanList[i].planDate) {
              rowspan++;
            } else {
              break;
            }
          }
        }
        return [rowspan, colspan]; // 返回合并行数和列数
      }
    },
    handleCellClick(row, column, event) {
      const cellValue = row[column.property];
      const detail = row[`detail_${column.property}`];
      console.log('Cell value:', cellValue);
      console.log(detail);
    },
    handleRowClick(row) {
      console.log('row value:', JSON.stringify(row));
    },
    handleDisable(row, index) {
      if (row.mplanStatus == '1') {
        return false
      } else {
        return true
      }
    },
    getCellStyles(row, prop) {
      let style = {};
      let detail = row[`detail_${prop}`];// 有可能有 undefined 对象，因为有些日期的产品多，有些日期的产品少
      if (detail && detail.bgColor) {
        style.backgroundColor = detail.bgColor;
      }
      // style.color = "black";
      return style;
    },
    init() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 月份需要加1，然后确保是两位数
      const day = currentDate.getDate().toString().padStart(2, '0'); // 获取日并确保是两位数
      this.queryParams.planMonth = `${year}-${month}`;
    },
    /** 查询订单信息列表 */
    getFactoryList() {
      this.loading = true;
      listFactory({"level":2}).then(response => {
        this.factoryList = response.data;
        // this.queryParams.factoryId = this.factoryList[0].deptId;
        // this.getTeamList(this.queryParams.factoryId);
        this.teamList = [];
        this.loading = false;
      });
    },
    factoryChange(){
      this.getTeamList(this.queryParams.factoryId);
    },
    /** 查询订单信息列表 */
    getTeamList(parentId) {
      this.loading = true;
      listTeam({"parentId":parentId}).then(response => {
        this.teamList = response.data;
        this.loading = false;
      });
    },

    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      bigPanListOfAll(this.queryParams).then(response => {
        this.bigPanList = response.data || [];
        this.columnList = response.columns || [];
        this.loading = false;
      }).catch(error => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planChooseMonth: null,
        workOrderIds: null
      };
      this.resetForm("form");
    },
    reset1() {
      this.form1 = {
        planMonth: null,
        mplanList: null
      };
      this.resetForm("form1");
    },
    /** 搜索按钮操作 */
    handleQuery(mock) {
      this.queryParams.excludeIds = [];
      this.queryParams.pageNum = 1;
      if(this.queryParams.teamId!=null && this.queryParams.teamId!=undefined){
        this.teamSelect = false;
      }
      this.queryParams.mock = mock;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery(false);
    },
  }
};
</script>
<style type="text/css">
  .el-progress-bar__innerText {
    color: white;
  }
</style>
